package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.UserRole;
import com.example.chamberlainserver.Service.UserRoleService;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户角色关联管理控制器
 */
@RestController
@RequestMapping("/api/user-roles")
public class UserRoleController {

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 获取用户的所有角色关联
     */
    @GetMapping("/user/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<List<UserRole>>> getUserRolesByUserId(@PathVariable Integer userId) {
        try {
            List<UserRole> userRoles = userRoleService.getUserRolesByUserId(userId);
            return ResponseEntity.ok(new ApiResponse<>(200, "获取用户角色关联成功", userRoles));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "获取用户角色关联失败: " + e.getMessage(), null));
        }
    }

    /**
     * 获取角色的所有用户关联
     */
    @GetMapping("/role/{roleId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<List<UserRole>>> getUserRolesByRoleId(@PathVariable Integer roleId) {
        try {
            List<UserRole> userRoles = userRoleService.getUserRolesByRoleId(roleId);
            return ResponseEntity.ok(new ApiResponse<>(200, "获取角色用户关联成功", userRoles));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "获取角色用户关联失败: " + e.getMessage(), null));
        }
    }

    /**
     * 添加用户角色关联
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<UserRole>> addUserRole(@RequestBody UserRole userRole) {
        try {
            boolean success = userRoleService.addUserRole(userRole);
            if (success) {
                return ResponseEntity.status(HttpStatus.CREATED)
                        .body(new ApiResponse<>(200, "添加用户角色关联成功", userRole));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(400, "添加用户角色关联失败", null));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "添加用户角色关联失败: " + e.getMessage(), null));
        }
    }

    /**
     * 批量添加用户角色关联
     */
    @PostMapping("/batch")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<List<UserRole>>> addUserRoles(@RequestBody List<UserRole> userRoles) {
        try {
            boolean success = userRoleService.batchAddUserRole(userRoles);
            if (success) {
                return ResponseEntity.status(HttpStatus.CREATED)
                        .body(new ApiResponse<>(200, "批量添加用户角色关联成功", userRoles));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(400, "批量添加用户角色关联失败", null));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "批量添加用户角色关联失败: " + e.getMessage(), null));
        }
    }

    /**
     * 删除用户的所有角色关联
     */
    @DeleteMapping("/user/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteUserRolesByUserId(@PathVariable Integer userId) {
        try {
            boolean success = userRoleService.deleteUserRolesByUserId(userId);
            if (success) {
                return ResponseEntity.ok(new ApiResponse<>(200, "删除用户角色关联成功", null));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(400, "删除用户角色关联失败", null));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "删除用户角色关联失败: " + e.getMessage(), null));
        }
    }

    /**
     * 删除角色的所有用户关联
     */
    @DeleteMapping("/role/{roleId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteUserRolesByRoleId(@PathVariable Integer roleId) {
        try {
            boolean success = userRoleService.deleteUserRolesByRoleId(roleId);
            if (success) {
                return ResponseEntity.ok(new ApiResponse<>(200, "删除角色用户关联成功", null));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(400, "删除角色用户关联失败", null));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "删除角色用户关联失败: " + e.getMessage(), null));
        }
    }

    /**
     * 删除特定的用户角色关联
     */
    @DeleteMapping("/user/{userId}/role/{roleId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteUserRoleByUserIdAndRoleId(
            @PathVariable Integer userId,
            @PathVariable Integer roleId) {
        try {
            boolean success = userRoleService.deleteUserRole(userId, roleId);
            if (success) {
                return ResponseEntity.ok(new ApiResponse<>(200, "删除用户角色关联成功", null));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(400, "删除用户角色关联失败", null));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "删除用户角色关联失败: " + e.getMessage(), null));
        }
    }

    /**
     * 检查用户是否拥有特定角色
     */
    @GetMapping("/check/user/{userId}/role/{roleId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Boolean>> hasRole(
            @PathVariable Integer userId,
            @PathVariable Integer roleId) {
        try {
            boolean hasRole = userRoleService.hasRole(userId, roleId);
            return ResponseEntity.ok(new ApiResponse<>(200, "检查用户角色成功", hasRole));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "检查用户角色失败: " + e.getMessage(), null));
        }
    }

    /**
     * 检查用户是否拥有特定角色（通过角色代码）
     */
    @GetMapping("/check/user/{userId}/role-code/{roleCode}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Boolean>> hasRoleByCode(
            @PathVariable Integer userId,
            @PathVariable String roleCode) {
        try {
            boolean hasRole = userRoleService.hasRoleByCode(userId, roleCode);
            return ResponseEntity.ok(new ApiResponse<>(200, "检查用户角色成功", hasRole));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(500, "检查用户角色失败: " + e.getMessage(), null));
        }
    }
}